// pages/message/index.ts
import { getUnreadMessages, markAllMessagesAsRead } from '../../utils/api/sysMessages';
import userBaseInfoState from '../../stores/userBaseInfo'
import { validateNull } from '../../utils/util';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // GPT仅支持在对话框中进行对话，不需要websocket
    sysMessage: {
      description: '展示发送人和发送类型',
    },
    messageList:[],
    hasUnreadMessages: false,
    patientUid: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    userBaseInfoState.bind(this, '$userBase');
    this.setData({
      patientUid: <string> userBaseInfoState.data.patientUid
    })
    this.checkUnreadMessages();
  },

  checkUnreadMessages() {
    const { patientUid } = this.data;
    if (!validateNull(patientUid)) {
      getUnreadMessages(<string> patientUid).then((res:any) => {
        if (res.data && Array.isArray(res.data)) {
          this.setData({
            messageList: res.data,
            hasUnreadMessages: res.data.length > 0
          });
        }
      })
      .catch((error:any) => {
        console.error('Error fetching unread messages:', error);
      });
    }
  },

  markMessagesAsRead() {
    if (this.data.messageList != null && this.data.messageList.length > 0) {
      const data = <any[]> []
      for (const key in this.data.messageList) {
        if (Object.prototype.hasOwnProperty.call(this.data.messageList, key)) {
          const element = this.data.messageList[key];
          data.push(element['notificationId'])
        }
      }
      markAllMessagesAsRead(data).then(() => {
          this.setData({
            hasUnreadMessages: false
          });
        })
        .catch((error:any) => {
          console.error('Error marking messages as read:', error);
        });
    }
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.checkUnreadMessages();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})